# -*- coding: utf-8 -*-
class PayablesController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  #before_filter :privilege_filter
  
  #显示新添加页面
  def newPayable
  end

  #显示编辑页面
  def editPayable
  end

  #应付列表
  def payablesList
    
  end
  
  def create
    begin
      payable = Payable.new
      payable.company_id = session[:company_id]
      payable.department_id = session[:department_id]
      payable.employee_id = session[:employee_id]
      payable.action_date = params[:action_date]
      payable.amount = params[:amount]
      payable.description = params[:description]
      payable.purchase_order_id = params[:purchase_order_id]
      payable.auditing_status = Constants::AUDIT_APPLY_ADD
      #给采购订单添加相应变化信息
      purchaseOrder = PurchaseOrder.find(params[:purchase_order_id])
      
      #判断一下，如果当前的付款金额已经大于采购金额会弹出提醒并退出。
      if purchaseOrder.paid_amount + payable.amount > purchaseOrder.amount
        info="您的付款金额已经超出了采购订单的采购金额！"
        result = "{success:true,info:'#{info}'}"
        render :text=>result, :layout=>false and return false
      end
      payable.vendor_id = purchaseOrder.vendor_id
      payable.save!
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end
    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def getPayableById
    payable = Payable.find(params[:id])
    rootStr = payable.to_json()
    jsonStr = "{root:["+rootStr+"]}"
    #logger.info jsonStr
    render :json=>jsonStr, :layout=>false
  end

  def update
    begin
      payable = Payable.find(params[:id])
      payable.action_date = params[:action_date]
      payable.description = params[:description]
      payable.vendor_id = PurchaseOrder.find(payable.purchase_order_id).vendor_id
      #如果是驳回新增，在编辑后，依然是申请新增
      if payable.auditing_status == Constants::REJECT_APPLY_ADD
        payable.auditing_status = Constants::AUDIT_APPLY_ADD
        payable.amount = params[:amount]
      else
        payable.auditing_status = Constants::AUDIT_APPLY_EDIT
        payable.new_amount = params[:amount]
      end
      payable.save!
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end
    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #得到所有的预付款
  def getAllPayables
    begin
      conditionsHash = Hash.new
      paramsHash = Hash.new
      start = params[:start]
      limit = params[:limit]
      conditionsStr = ''

      if params[:auditing_status].to_s != '' && params[:auditing_status] != ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status like :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
        end
        conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
      elsif params[:auditing_status] == ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status = :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status = :auditing_status'
        end
        conditionsHash[:auditing_status] = ''
      end

      if params[:vendor_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'vendor_id = :vendor_id'
        else
          conditionsStr = conditionsStr+' AND vendor_id = :vendor_id'
        end
        conditionsHash[:vendor_id] = params[:vendor_id].to_i
      end

      if params[:begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date >= :begin_date'
        else
          conditionsStr = conditionsStr+' AND action_date >= :begin_date'
        end
        conditionsHash[:begin_date] = params[:begin_date].to_date
      end

      if params[:end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date <= :end_date'
        else
          conditionsStr = conditionsStr+' AND action_date <= :end_date'
        end
        conditionsHash[:end_date] = params[:end_date].to_date
      end

      payables = Payable.find_all conditionsStr,conditionsHash
      payablesNow = payables.paginate start,limit

      jsonStr="{totalProperty:"+payables.length.to_s+",root:"+payablesNow.to_json(:include=>{:purchase_order=>{:only=>[:order_number,:auditing_status]},:auditor=>{},:employee=>{},:vendor=>{}})+"}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #审批，审批后，才计入销售订单的已付帐款
  def updateAuditingStatus
    payable = Payable.find(params[:id])
    info = nil
    if payable !=nil
      Payable.transaction do
        auditingStatus = params[:auditing_status]
        payable.auditor_id = session[:employee_id]
        payable.audit_opinion =  params[:audit_opinion]
        payable.type_of_payment =  params[:type_of_payment]
        if(auditingStatus == "是")
          purchaseOrder = payable.purchase_order
          if payable.auditing_status == Constants::AUDIT_APPLY_EDIT
            auditingStatus = Constants::PASS_APPLY_EDIT
            purchaseOrder.paid_amount = purchaseOrder.paid_amount - payable.amount
            payable.amount = payable.new_amount
            payable.new_amount = nil
            purchaseOrder.paid_amount = purchaseOrder.paid_amount + payable.amount
            purchaseOrder.save!
          else
            auditingStatus = Constants::PASS_APPLY_ADD
            purchaseOrder.paid_amount = purchaseOrder.paid_amount + payable.amount
            purchaseOrder.save!
          end
          payable.auditing_status = auditingStatus
        else
          if payable.auditing_status == Constants::AUDIT_APPLY_EDIT
            auditingStatus = Constants::REJECT_APPLY_EDIT
          else
            auditingStatus = Constants::REJECT_APPLY_ADD
          end
          payable.auditing_status = auditingStatus
        end
        payable.save!
      end
      #结算表处理完毕。
      info = "成功"
    else
      info = "失败"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #根据审批的结果
  def updateAuditingCancelStatus
    payable = Payable.find(params[:id])
    Payable.transaction do
      if params[:auditing_status]=='是'
        payable.auditing_status = Constants::PASS_APPLY_CANCEL
        payable.audit_opinion = params[:audit_opinion]
        #去掉销售订单中的相关金额
        purchaseOrder = PurchaseOrder.find(payable.purchase_order_id)
        purchaseOrder.paid_amount = purchaseOrder.paid_amount - payable.amount
        purchaseOrder.save!
      else
        payable.audit_opinion = params[:audit_opinion]
        payable.auditing_status = Constants::REJECT_APPLY_CANCEL
      end

      payable.auditor_id = session[:employee_id]
      payable.save!
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #申请撤消
  def applyToCancel
    payable = Payable.find(params[:id])
    #如果是通过新增则要审批，如果是申请状态则直接撤消
    if payable.auditing_status == Constants::PASS_APPLY_ADD
      payable.auditing_status = Constants::AUDIT_APPLY_CANCEL
    else
      payable.auditing_status = Constants::PASS_APPLY_CANCEL
    end
    payable.auditor_id = session[:employee_id]
    payable.save!

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
end
